package com.woniuxy.login.controller;

import com.woniuxy.common.CommonResult;
import com.woniuxy.login.client.PersonServiceFeignClient;
import com.woniuxy.login.client.dto.PlUser;
import com.woniuxy.login.client.dto.UserDto;
import com.woniuxy.login.exception.SeckillException;
import com.woniuxy.login.util.RandomNumber;
import com.woniuxy.login.util.SendMsgUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * Date: 2021/7/7:16:19  <br/>
 * Description:
 */
@RestController
@RequestMapping("/phoneLogin")
@Api(tags = "手机号注册")
public class PhoneLoginController {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private PersonServiceFeignClient client;

    @GetMapping("sendMes/{phone}")
    @ApiOperation("获取验证码")
    public void sendMes(@PathVariable("phone") String phone){
        String code = RandomNumber.getRandomNumberString();
        CommonResult<PlUser> plUserCommonResult = client.selectUser(phone);
        if (plUserCommonResult.getData() != null){
            throw new SeckillException(500,"此账号已注册，请前往登陆");
        }

        try {
            SendMsgUtil.sedMsg(phone,code);
        } catch (Exception e) {
            e.printStackTrace();
        }
        redisTemplate.opsForList().rightPush("code:"+phone,code);
    }

    @PostMapping("phoneLogin")
    @ApiOperation("注册")
    public CommonResult phoneLogin(@RequestBody UserDto userDto){
        String phone = userDto.getPhone();
        String code = userDto.getCode();
        System.out.println("从前端中获取code:"+code);
        String codeRedis = (String) redisTemplate.opsForList().leftPop("code:"+phone);
        System.out.println("从redis中获取code:"+codeRedis);
        if (code.equals(codeRedis)){
            CommonResult commonResult = client.insertUser(userDto);
            if (commonResult.getCode() == 200){
                return CommonResult.success("注册成功请登录");
            }
        }
        return CommonResult.fail("注册失败");
    }
}
